<script setup lang="ts">
import { computed } from 'vue';
import { NTag, NDescriptions, NDescriptionsItem, NButton } from 'naive-ui';
import { fetchGetRecordUrl } from '@/service/api/outbound';
import { $t } from '@/locales';

defineOptions({
  name: 'RecordDetailModal'
});

interface Props {
  visible: boolean;
  record: Api.Outbound.CallRecord | null;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

function closeModal() {
  visible.value = false;
}

const callResultText = computed(() => {
  if (!props.record?.callResult) return '-';

  const statusMap: Record<number, string> = {
    1: '正常接通',
    2: '关机',
    3: '停机',
    4: '空号',
    6: '暂时无法接通',
    7: '无人接听',
    8: '被叫忙',
    9: '被叫拒接',
    2000: '未接通'
  };

  return statusMap[props.record.callResult] || '未知';
});

const durationText = computed(() => {
  if (!props.record?.durationInMs || props.record.durationInMs <= 0) return '-';

  const seconds = Math.floor(props.record.durationInMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
});

const dialogContent = computed(() => {
  if (!props.record?.dialogContent) return null;

  try {
    return JSON.parse(props.record.dialogContent);
  } catch {
    return null;
  }
});

const slots = computed(() => {
  if (!props.record?.slots) return null;

  try {
    return JSON.parse(props.record.slots);
  } catch {
    return null;
  }
});

const labels = computed(() => {
  if (!props.record?.labels) return null;

  try {
    return JSON.parse(props.record.labels);
  } catch {
    return null;
  }
});

async function handleViewRecord() {
  if (!props.record?.callId) return;

  try {
    const { data } = await fetchGetRecordUrl(props.record.callId);
    if (data?.recordUrl) {
      window.open(data.recordUrl, '_blank');
    } else {
      window.$message?.warning('录音文件不存在或未生成');
    }
  } catch (error) {
    console.error('获取录音失败:', error);
    window.$message?.error('获取录音失败');
  }
}
</script>

<template>
  <NModal v-model:show="visible" :mask-closable="false" preset="card" title="通话记录详情" class="w-1000px">
    <div v-if="record" class="space-y-16px">
      <!-- 基本信息 -->
      <NDescriptions title="基本信息" :column="3" bordered>
        <NDescriptionsItem label="通话ID">
          {{ record.callId }}
        </NDescriptionsItem>
        <NDescriptionsItem label="会话ID">
          {{ record.sessionId || '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="任务ID">
          {{ record.taskId }}
        </NDescriptionsItem>
        <NDescriptionsItem label="主叫号码">
          {{ record.caller }}
        </NDescriptionsItem>
        <NDescriptionsItem label="被叫号码">
          {{ record.callee }}
        </NDescriptionsItem>
        <NDescriptionsItem label="通话状态">
          <NTag :type="record.callResult === 1 ? 'success' : 'error'">
            {{ callResultText }}
          </NTag>
        </NDescriptionsItem>
      </NDescriptions>

      <!-- 通话时间信息 -->
      <NDescriptions title="时间信息" :column="2" bordered>
        <NDescriptionsItem label="呼叫开始时间">
          {{ record.startTime ? new Date(record.startTime).toLocaleString() : '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="振铃时间">
          {{ record.ringTime ? new Date(record.ringTime).toLocaleString() : '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="接通时间">
          {{ record.answerTime ? new Date(record.answerTime).toLocaleString() : '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="结束时间">
          {{ record.endTime ? new Date(record.endTime).toLocaleString() : '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="通话时长">
          {{ durationText }}
        </NDescriptionsItem>
        <NDescriptionsItem label="通话轮次">
          {{ record.dialogRound || '-' }}
        </NDescriptionsItem>
      </NDescriptions>

      <!-- 意向信息 -->
      <NDescriptions title="意向信息" :column="3" bordered>
        <NDescriptionsItem label="意向等级">
          <NTag v-if="record.intentionGrading" :type="record.intentionGrading === 'A' ? 'success' : 'warning'">
            {{ record.intentionGrading }}
          </NTag>
          <span v-else>-</span>
        </NDescriptionsItem>
        <NDescriptionsItem label="意向描述">
          {{ record.gradingDescription || '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="挂机方">
          <NTag v-if="record.isUserHangup !== null" :type="record.isUserHangup ? 'error' : 'info'">
            {{ record.isUserHangup ? '用户挂机' : '机器人挂机' }}
          </NTag>
          <span v-else>-</span>
        </NDescriptionsItem>
      </NDescriptions>

      <!-- 短信信息 -->
      <NDescriptions v-if="record.smsContent || record.smsStatus" title="短信信息" :column="2" bordered>
        <NDescriptionsItem label="短信状态">
          {{ record.smsStatus || '-' }}
        </NDescriptionsItem>
        <NDescriptionsItem label="短信内容">
          {{ record.smsContent || '-' }}
        </NDescriptionsItem>
      </NDescriptions>

      <!-- 槽位信息 -->
      <div v-if="slots && Array.isArray(slots) && slots.length > 0">
        <h4 class="text-14px font-semibold mb-8px">槽位信息</h4>
        <div class="flex flex-wrap gap-8px">
          <NTag v-for="slot in slots" :key="slot.Key" type="info" size="small">
            {{ slot.Key }}: {{ slot.Value }}
          </NTag>
        </div>
      </div>

      <!-- 标签信息 -->
      <div v-if="labels && Array.isArray(labels) && labels.length > 0">
        <h4 class="text-14px font-semibold mb-8px">标签信息</h4>
        <div class="flex flex-wrap gap-8px">
          <NTag v-for="label in labels" :key="label.LabelId || label.LabelValue" type="success" size="small">
            {{ label.LabelName || label.LabelValue }}
          </NTag>
        </div>
      </div>

      <!-- 对话内容 -->
      <div v-if="dialogContent && Array.isArray(dialogContent)">
        <h4 class="text-14px font-semibold mb-8px">对话内容</h4>
        <div class="max-h-300px overflow-y-auto space-y-8px border border-gray-200 rounded p-12px">
          <div v-for="(dialog, index) in dialogContent" :key="index" class="space-y-4px">
            <div v-if="dialog.Request?.Text" class="text-right">
              <div class="inline-block bg-blue-100 text-blue-800 px-8px py-4px rounded text-12px max-w-2/3">
                用户：{{ dialog.Request.Text }}
              </div>
            </div>
            <div v-if="dialog.Response?.Text" class="text-left">
              <div class="inline-block bg-gray-100 text-gray-800 px-8px py-4px rounded text-12px max-w-2/3">
                机器人：{{ dialog.Response.Text.replace(/<[^>]*>/g, '') }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 录音操作 -->
      <div class="flex justify-center pt-16px">
        <NButton type="primary" @click="handleViewRecord">
          <template #icon>
            <icon-ic-round-play-circle class="text-icon" />
          </template>
          播放录音
        </NButton>
      </div>
    </div>

    <template #footer>
      <NSpace :size="16">
        <NButton @click="closeModal">{{ $t('common.close') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
